/* Copyright 2014 Jan Wolter */

#include "stack.h"
#include "waste.h"

/* Array of waste piles used in this game */
WasteStack *waste;
int wastesize= 0;	/* current size of waste array */

/* Only the top card of the waste is movable */
int waste_firstMove(Stack *stack, int *index1, int *len)
{
    if (stack->n == 0) return 0;
    *index1= stack->n-1;
    *len= 1;
    return 1;
}

int waste_nextMove(Stack *stack, int *index1, int *len)
{
    return 0;
}

void makeWaste()
{
    /* Make sure we have memory for another waste pile */
    if (wastesize == 0)
    {
	wastesize= 1;
	waste= (WasteStack *)malloc(wastesize*sizeof(WasteStack));
    }
    else if (nwaste == wastesize)
    {
	wastesize+= 3;
	waste= (WasteStack *)realloc(waste,wastesize*sizeof(WasteStack));
    }

    /* It starts out empty, but we allocate enough memory for it to be full */
    /* mayInsert is null since we can't move cards to the waste (a deal is */
    /* not a move) */
    waste[nwaste].id= newStack(WASTE,nwaste,26,
	    NULL, waste_firstMove, waste_nextMove, NULL);

    nwaste++;
}

void cleanWaste()
{
    free(waste);
    nwaste= wastesize= 0;
}

void printWaste(FILE *f, Stack *stks)
{
    char label[8];
    for (int k= 0; k < nwaste; k++)
    {
	sprintf(label,"W%02d", k+1);
	printStack(f, label, stks+waste[k].id);
    }
}

/* Concatinate all cards from waste in reverse order onto the given stack. If
 * empty is true, we empty the waste, otherwise the waste is unaltered.
 */
void gatherWaste(Stack *s, int empty)
{
    for (int k= 0; k < nwaste; k++)
    {
	Stack *ws= stacks+waste[k].id;
	appendStack(s, ws, 1);
	if (empty) ws->n= 0;
    }
}

int wasteid(int i)
{
    return waste[i].id;
}
